package com.itheima.config;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itheima.Mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Component
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<com.itheima.pojo.User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_name",username);
        com.itheima.pojo.User mysqlUser=userMapper.selectOne(queryWrapper);
        Collection<GrantedAuthority> authorities=new ArrayList<>();

        List<String> list= userMapper.selectRoles(username);
        if(list!=null && list.size()>0){
            for(String role:list){
                authorities.add(new SimpleGrantedAuthority(role));
            }
        }
        if(mysqlUser==null){
            return null;
        }
        User user=new User(mysqlUser.getUserName(), mysqlUser.getPassword(), authorities);
        return user;
    }
}